using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace WpfApp1.ViewModels;

public partial class MainViewModel : ObservableObject
{
    [ObservableProperty]
    private ObservableCollection<TabItemViewModel> _tabs;

    [ObservableProperty]
    private TabItemViewModel _selectedTab;

    private int _counter = 1;

    public MainViewModel()
    {
        Tabs = new ObservableCollection<TabItemViewModel>();
        AddInitialTabs();
    }

    private void AddInitialTabs()
    {
        for (int i = 1; i <= 5; i++)
        {
            var tab = new TabItemViewModel($"Tab {i}", $"This is the content of Tab {i}");
            tab.CloseRequested += OnTabCloseRequested;
            Tabs.Add(tab);
        }
        SelectedTab = Tabs[0];
    }

    [RelayCommand]
    private void AddTab()
    {
        var tab = new TabItemViewModel($"New Tab {_counter++}", $"This is a new tab created at {DateTime.Now}");
        tab.CloseRequested += OnTabCloseRequested;
        Tabs.Add(tab);
        SelectedTab = tab;
    }

    private void OnTabCloseRequested(TabItemViewModel viewModel)
    {
        if (Tabs.Count > 1)
        {
            int index = Tabs.IndexOf(viewModel);
            if (index > 0)
            {
                SelectedTab = Tabs[index - 1];
            }
            else
            {
                SelectedTab = Tabs[1];
            }
        }
        Tabs.Remove(viewModel);
        viewModel.CloseRequested -= OnTabCloseRequested;
    }
}
